import axios from 'axios';
import { ElLoading, ElMessage } from 'element-plus';
let loadingInstance = null; // loading 实例

class Http {
  // options = {}
  constructor(instance) {
    this.instance = instance

    // 添加请求拦截器
    this.instance.interceptors.request.use(config => {
      config.headers.Authorization = localStorage.getItem("token")
      // 显示 loading
      if (config.showLoading) {
        loadingInstance = ElLoading.service({
          text:"拼命加载中",
          background:'rgba(0, 0, 0, 0.7)'
        });
      }
      return config;
    }, error => {
        // 对请求错误做些什么
        loadingInstance.close(); // 关闭 loading
        console.log("请求出错了")
       return Promise.reject(error);
    });

    // 添加响应拦截器
    this.instance.interceptors.response.use(response => {
        let authorization  = response.headers["authorization"]
        // 存储token
        authorization && localStorage.setItem("token",authorization)
        // 关闭 loading
        loadingInstance.close(); 
        return response.data;
    }, error => {
         // 关闭 loading
         loadingInstance.close(); 
        let { status } = error.response
        // token过期跳转到登录页面
        if( status == 401){
          window.location.href = "#/login"
        }
     
        // return Promise.reject(error);
    });
  }

  get(url, showLoading = false) {
    let config = {
      showLoading,
    }
    return this.request({
      method: 'GET',
      url,
      ...config
    });
  }

  post(url, data = {}, showLoading = false) {
    let config = {
      showLoading,
    }
    return this.request({
      method: 'POST',
      url,
      data,
      ...config
    });
  }

  request(config) {
    return this.instance.request(config);
  }
}

export default Http;